package com.lxw.weather.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import android.util.Log;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;

import com.lxw.weather.R;
import com.lxw.weather.adapter.HourlyForecastAdapter;
import com.lxw.weather.adapter.Observe24hAdapter;
import com.lxw.weather.model.HourlyForecast;
import com.lxw.weather.model.DailyForecast;
import com.lxw.weather.model.LifeIndex;
import com.lxw.weather.model.Observe24hData;
import com.lxw.weather.util.UpdateManager;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.viewpager2.adapter.FragmentStateAdapter; // 正确导入

public class MainActivity extends AppCompatActivity {

    private TextView cityNameText, currentTempText, weatherConditionText,
            windText, humidityText, pressureText, aqiText, visibilityText, windDirectionText, alarmMarquee;
    private EditText searchInput;
    private Button searchBtn, cityManagerBtn, showForecastBtn, toggleDayNightBtn;
    private ImageView weatherIcon;
    private Handler handler;
    private List<HourlyForecast> hourlyForecastList = new ArrayList<>();

    private List<DailyForecast> cachedDailyForecasts = new ArrayList<>();
    private List<DailyForecast> cached15DayForecasts = new ArrayList<>();

    private String dayWeatherPic;
    private String nightWeatherPic;
    private boolean isDayTime = true;
    private RecyclerView hourlyForecastRecyclerView;
    private RecyclerView observe24hRecyclerView; // 新增
    private Observe24hAdapter observe24hAdapter; // 新增
    private LifeIndex lifeIndex; // 新增：保存生活指数数据的引用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initUIComponents();
        handler = new Handler(Looper.getMainLooper());

        // 检查版本更新
        new UpdateManager(this).checkUpdate();

        // 读取默认城市
        String defaultCity = getSharedPreferences("weather_prefs", MODE_PRIVATE)
            .getString("default_city", "北京");
        fetchWeatherData("areaCn", defaultCity);
    }

    private void initUIComponents() {
        // 初始化UI组件...
        cityNameText = findViewById(R.id.cityName);
        currentTempText = findViewById(R.id.currentTemp);
        weatherConditionText = findViewById(R.id.weatherCondition);
        windText = findViewById(R.id.wind);
        humidityText = findViewById(R.id.humidity);
        pressureText = findViewById(R.id.pressure);
        aqiText = findViewById(R.id.aqi);
        visibilityText = findViewById(R.id.visibility);
        windDirectionText = findViewById(R.id.windDirection);
        alarmMarquee = findViewById(R.id.alarmMarquee); // 新增：初始化预警信息控件

        searchInput = findViewById(R.id.searchInput);
        searchBtn = findViewById(R.id.searchBtn);
        cityManagerBtn = findViewById(R.id.cityManagerBtn);
        showForecastBtn = findViewById(R.id.showForecastBtn);
        toggleDayNightBtn = findViewById(R.id.toggleDayNightBtn);
        weatherIcon = findViewById(R.id.weatherIcon);

        // 新增：生活指数按钮
        Button lifeIndexBtn = findViewById(R.id.weatherIndexBtn);
        lifeIndexBtn.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, WeatherIndexActivity.class);
            intent.putExtra("aqiData", aqiText.getText().toString());
            
            // 从now对象获取PM2.5值
            String pm25Value = now.optString("aqi_pm25", "未知");
            Log.d("MainActivity", "传递给WeatherIndexActivity的PM2.5值: " + pm25Value);
            intent.putExtra("pm25Data", pm25Value);
            
            intent.putExtra("humidityData", humidityText.getText().toString());
            intent.putExtra("pressureData", pressureText.getText().toString());
            intent.putExtra("visibilityData", visibilityText.getText().toString());
            startActivity(intent);
        });

        // 新增：生活指数按钮（修复部分）
        Button realLifeIndexBtn = findViewById(R.id.lifeIndexBtn);
        realLifeIndexBtn.setOnClickListener(v -> {
            if (lifeIndex != null) {
                Intent intent = new Intent(MainActivity.this, LifeIndexActivity.class);
                intent.putExtra("lifeIndexData", lifeIndex);
                startActivity(intent);
            } else {
                Toast.makeText(MainActivity.this, "生活指数数据未加载", Toast.LENGTH_SHORT).show();
            }
        });

        // 添加RecyclerView初始化代码
        hourlyForecastRecyclerView = findViewById(R.id.hourlyForecastRecyclerView);
        hourlyForecastRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        // 添加ItemDecoration设置左右间距
        hourlyForecastRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                // 设置左右间距为16dp（注意：这里是像素单位，实际使用时建议转为dp）
                int spacing = (int) (16 * getResources().getDisplayMetrics().density);
                outRect.left = spacing;
                outRect.right = spacing;
            }
        });

        hourlyForecastRecyclerView.setAdapter(new HourlyForecastAdapter(hourlyForecastList, this));

        // 初始化24小时观测数据RecyclerView
        observe24hRecyclerView = findViewById(R.id.observe24hRecyclerView);
        observe24hRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        observe24hAdapter = new Observe24hAdapter(new ArrayList<>());
        observe24hRecyclerView.setAdapter(observe24hAdapter);

        // 添加间距装饰
        observe24hRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.right = 16; // 设置项之间的右边距
            }
        });

        // 设置按钮点击事件...
        showForecastBtn.setOnClickListener(v -> {
            if (!cachedDailyForecasts.isEmpty() && !cached15DayForecasts.isEmpty()) {
                Intent intent = new Intent(MainActivity.this, ForecastActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("forecast7dData", new ArrayList<>(cachedDailyForecasts));
                bundle.putParcelableArrayList("forecast15dData", new ArrayList<>(cached15DayForecasts));
                intent.putExtra("forecastBundle", bundle);
                startActivity(intent);
            } else {
                Toast.makeText(this, "7天/15天数据未加载完成", Toast.LENGTH_SHORT).show();
            }
        });

        searchBtn.setOnClickListener(v -> {
            String query = searchInput.getText().toString().trim();
            if (!query.isEmpty()) {
                if (query.matches("\\d+")) {
                    fetchWeatherData("areaCode", query);
                } else if (query.matches("-?\\d+\\.\\d+,-?\\d+\\.\\d+")) {
                    fetchWeatherData("location", query);
                } else {
                    fetchWeatherData("areaCn", query);
                }
            }
        });

        cityManagerBtn.setOnClickListener(v -> {
            startActivityForResult(new Intent(MainActivity.this, CityManagerActivity.class), 1);
        });

        toggleDayNightBtn.setOnClickListener(v -> {
            isDayTime = !isDayTime;
            updateWeatherIcon();
        });
    }

    private void fetchWeatherData(String queryType, String queryValue) {
        new Thread(() -> {
            try {
                // 请求实时天气数据
                String path1d = "https://getweather.api.bdymkt.com/lundear/weather1d";
                ApiExplorerRequest request1d = createBaseRequest(path1d, queryType, queryValue);
                request1d.addQueryParameter("need3hour", "1");
                request1d.addQueryParameter("needObserve", "1");
                request1d.addQueryParameter("needIndex", "1"); // 添加生活指数请求参数
                ApiExplorerResponse response1d = new ApiExplorerClient(new AppSigner()).sendRequest(request1d);

                // 请求7天和15天预报数据...
                String path7d = "https://getweather.api.bdymkt.com/lundear/weather7d";
                ApiExplorerRequest request7d = createBaseRequest(path7d, queryType, queryValue);
                ApiExplorerResponse response7d = new ApiExplorerClient(new AppSigner()).sendRequest(request7d);

                String path15d = "https://getweather.api.bdymkt.com/lundear/weather15d";
                ApiExplorerRequest request15d = createBaseRequest(path15d, queryType, queryValue);
                ApiExplorerResponse response15d = new ApiExplorerClient(new AppSigner()).sendRequest(request15d);

                // 整合数据并更新UI
                JSONObject result = new JSONObject();
                result.put("realTime", new JSONObject(response1d.getResult()));
                result.put("forecast7d", new JSONObject(response7d.getResult()));
                result.put("forecast15d", new JSONObject(response15d.getResult()));

                updateWeatherUI(result.toString());
            } catch (Exception e) {
                e.printStackTrace();
                handler.post(() ->
                        Toast.makeText(MainActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show()
                );
            }
        }).start();
    }

    private ApiExplorerRequest createBaseRequest(String path, String queryType, String queryValue) {

        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.GET, path);
        request.setCredentials("bfa3a60f38c24840bfdad3947f14b8a5", "b5211565d0ed46a78218775b3a7d2b8c");
        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");

        // 设置通用查询参数...
        request.addQueryParameter("areaCn", "");
        request.addQueryParameter("areaCode", "");
        request.addQueryParameter("ip", "");
        request.addQueryParameter("lat", "");
        request.addQueryParameter("lng", "");
        request.addQueryParameter("need3hour", "0");
        request.addQueryParameter("needIndex", "0");
        request.addQueryParameter("needObserve", "0");
        request.addQueryParameter("needalarm", "1"); // 修改为1
        request.addQueryParameter("need1hour", "0");

        // 根据查询类型设置具体参数...
        if (queryType.equals("location")) {
            String[] parts = queryValue.split(",");
            request.addQueryParameter("lat", parts[0]);
            request.addQueryParameter("lng", parts[1]);
        } else if (queryType.equals("areaCode")) {
            request.addQueryParameter("areaCode", queryValue);
        } else {
            request.addQueryParameter("areaCn", queryValue);
        }

        return request;
    }

    // 在类成员变量区域添加now变量声明
    private JSONObject now; // 新增
    
    // 在updateWeatherUI方法中为now变量赋值
    private void updateWeatherUI(String result) {
        handler.post(() -> {
            try {
                Log.d("MainActivity", "完整API响应: " + result);
                JSONObject jsonResponse = new JSONObject(result);
    
                // 处理实时天气数据
                JSONObject realTime = jsonResponse.getJSONObject("realTime");
                if ("0".equals(realTime.getString("code"))) {
                    JSONObject data = realTime.getJSONObject("data");
                    this.now = data.getJSONObject("now"); // 修改为成员变量赋值
                    JSONObject cityInfo = data.getJSONObject("cityInfo");
    
                    // 新增：解析生活指数数据
                    lifeIndex = new LifeIndex();
                    if (data.has("lifeIndex") && !data.isNull("lifeIndex")) {
                        Log.d("MainActivity", "生活指数数据存在");
                        JSONObject lifeIndexJson = data.getJSONObject("lifeIndex");
    
                        // 解析穿衣指数
                        if (lifeIndexJson.has("穿衣指数") && !lifeIndexJson.isNull("穿衣指数")) {
                            LifeIndex.DressIndex dressIndex = new LifeIndex.DressIndex();
                            dressIndex.setState(lifeIndexJson.getJSONObject("穿衣指数").getString("state"));
                            dressIndex.setReply(lifeIndexJson.getJSONObject("穿衣指数").getString("reply"));
                            lifeIndex.setDressIndex(dressIndex);
                            Log.d("MainActivity", "穿衣指数解析完成: state=" + dressIndex.getState() + ", reply=" + dressIndex.getReply());
                        } else {
                            Log.e("MainActivity", "穿衣指数数据不存在或为null");
                        }
    
                        // 解析紫外线指数
                        if (lifeIndexJson.has("紫外线指数") && !lifeIndexJson.isNull("紫外线指数")) {
                            LifeIndex.UvIndex uvIndex = new LifeIndex.UvIndex();
                            uvIndex.setState(lifeIndexJson.getJSONObject("紫外线指数").getString("state"));
                            uvIndex.setReply(lifeIndexJson.getJSONObject("紫外线指数").getString("reply"));
                            lifeIndex.setUvIndex(uvIndex);
                            Log.d("MainActivity", "紫外线指数解析完成: state=" + uvIndex.getState() + ", reply=" + uvIndex.getReply());
                        } else {
                            Log.e("MainActivity", "紫外线指数数据不存在或为null");
                        }
    
                        // 解析感冒指数
                        if (lifeIndexJson.has("感冒指数") && !lifeIndexJson.isNull("感冒指数")) {
                            LifeIndex.ColdIndex coldIndex = new LifeIndex.ColdIndex();
                            coldIndex.setState(lifeIndexJson.getJSONObject("感冒指数").getString("state"));
                            coldIndex.setReply(lifeIndexJson.getJSONObject("感冒指数").getString("reply"));
                            lifeIndex.setColdIndex(coldIndex);
                            Log.d("MainActivity", "感冒指数解析完成: state=" + coldIndex.getState() + ", reply=" + coldIndex.getReply());
                        } else {
                            Log.e("MainActivity", "感冒指数数据不存在或为null");
                        }
    
                        // 解析洗车指数
                        if (lifeIndexJson.has("洗车指数") && !lifeIndexJson.isNull("洗车指数")) {
                            LifeIndex.CarWashIndex carWashIndex = new LifeIndex.CarWashIndex();
                            carWashIndex.setState(lifeIndexJson.getJSONObject("洗车指数").getString("state"));
                            carWashIndex.setReply(lifeIndexJson.getJSONObject("洗车指数").getString("reply"));
                            lifeIndex.setCarWashIndex(carWashIndex);
                            Log.d("MainActivity", "洗车指数解析完成: state=" + carWashIndex.getState() + ", reply=" + carWashIndex.getReply());
                        } else {
                            Log.e("MainActivity", "洗车指数数据不存在或为null");
                        }
    
                        // 解析运动指数
                        if (lifeIndexJson.has("运动指数") && !lifeIndexJson.isNull("运动指数")) {
                            LifeIndex.SportIndex sportIndex = new LifeIndex.SportIndex();
                            sportIndex.setState(lifeIndexJson.getJSONObject("运动指数").getString("state"));
                            sportIndex.setReply(lifeIndexJson.getJSONObject("运动指数").getString("reply"));
                            lifeIndex.setSportIndex(sportIndex);
                            Log.d("MainActivity", "运动指数解析完成: state=" + sportIndex.getState() + ", reply=" + sportIndex.getReply());
                        } else {
                            Log.e("MainActivity", "运动指数数据不存在或为null");
                        }
    
                        // 解析过敏指数
                        if (lifeIndexJson.has("过敏指数") && !lifeIndexJson.isNull("过敏指数")) {
                            LifeIndex.AllergyIndex allergyIndex = new LifeIndex.AllergyIndex();
                            allergyIndex.setState(lifeIndexJson.getJSONObject("过敏指数").getString("state"));
                            allergyIndex.setReply(lifeIndexJson.getJSONObject("过敏指数").getString("reply"));
                            lifeIndex.setAllergyIndex(allergyIndex);
                            Log.d("MainActivity", "过敏指数解析完成: state=" + allergyIndex.getState() + ", reply=" + allergyIndex.getReply());
                        } else {
                            Log.e("MainActivity", "过敏指数数据不存在或为null");
                        }
                    } else {
                        Log.e("MainActivity", "lifeIndex字段不存在或为null");
                    }
                    // 更新UI组件...
                    if (cityNameText != null) {
                        cityNameText.setText(cityInfo.optString("areaCn", "未知城市"));
                    }
    
                    if (currentTempText != null) {
                        currentTempText.setText(now.optString("temp", "N/A"));
                    }
    
                    if (weatherConditionText != null) {
                        weatherConditionText.setText(now.optString("weather", "未知天气"));
                    }
    
                    if (windText != null) {
                        windText.setText("风力: " + now.optString("WS", "未知"));
                    }
    
                    if (windDirectionText != null) {
                        windDirectionText.setText("风向: " + now.optString("WD", "未知"));
                    }
    
                    if (humidityText != null) {
                        humidityText.setText("湿度: " + now.optString("SD", "未知"));
                    }
    
                    if (pressureText != null) {
                        pressureText.setText("气压: " + now.optString("qy", "未知"));
                    }
    
                    if (aqiText != null) {
                        String aqiValue = now.optString("aqi", "未知");
                        aqiText.setText("空气质量: " + aqiValue);
                        Log.d("MainActivity", "AQI值: " + aqiValue);
                        
                        // 修改为从now对象获取aqi_pm25字段
                        String pm25Value = now.optString("aqi_pm25", "未知");
                        Log.d("MainActivity", "PM2.5值: " + pm25Value);
                    }
    
                    if (visibilityText != null) {
                        visibilityText.setText("能见度: " + now.optString("njd", "未知"));
                    }
    
                    // 更新天气图标
                    try {
                        JSONObject dayData = data.optJSONObject("day");
                        JSONObject nightData = data.optJSONObject("night");
    
                        if (dayData != null) {
                            dayWeatherPic = dayData.optString("weather_pic", "d00");
                        } else {
                            dayWeatherPic = "d00";
                            Log.e("MainActivity", "dayData is null!");
                        }
    
                        if (nightData != null) {
                            nightWeatherPic = nightData.optString("weather_pic", "n00");
                        } else {
                            nightWeatherPic = "n00";
                            Log.e("MainActivity", "nightData is null!");
                        }
    
                        updateWeatherIcon();
                    } catch (Exception e) {
                        Log.e("MainActivity", "获取天气图标失败: " + e.getMessage());
                        dayWeatherPic = "d00";
                        nightWeatherPic = "n00";
                        updateWeatherIcon();
                    }
    
                    // 解析并更新小时预报数据
                    parseHourlyForecast(data);
                    // 添加24小时观测数据解析
                    parseObserve24hData(data);
    
                    // 解析并显示天气预警数据
                    if (alarmMarquee != null) {
                        if (data.has("alarmList") && !data.isNull("alarmList")) {
                            JSONArray alarmList = data.getJSONArray("alarmList");
                            if (alarmList.length() > 0) {
                                StringBuilder alarmContent = new StringBuilder();
                                for (int i = 0; i < alarmList.length(); i++) {
                                    JSONObject alarm = alarmList.getJSONObject(i);
                                    alarmContent.append(alarm.optString("signalType"))
                                            .append(alarm.optString("signalLevel"))
                                            .append(": ")
                                            .append(alarm.optString("issueContent"))
                                            .append(" ");
                                }
                                alarmMarquee.setText(alarmContent.toString());
                                alarmMarquee.setVisibility(View.VISIBLE);
                                alarmMarquee.setSelected(true); // 启用跑马灯效果
                            } else {
                                alarmMarquee.setVisibility(View.GONE);
                            }
                        } else {
                            alarmMarquee.setVisibility(View.GONE);
                        }
                    }
                }
    
                // 处理7天预报数据...
                JSONObject forecast7d = jsonResponse.getJSONObject("forecast7d");
                if ("0".equals(forecast7d.getString("code"))) {
                    JSONObject forecastData = forecast7d.getJSONObject("data");
                    cachedDailyForecasts.clear();
    
                    for (int i = 1; i <= 7; i++) {
                        String dayKey = "d" + i;
                        if (forecastData.has(dayKey)) {
                            JSONObject dayData = forecastData.getJSONObject(dayKey);
                            DailyForecast dailyForecast = parseDailyForecast(dayData, true);
                            cachedDailyForecasts.add(dailyForecast);
                        }
                    }
                }
    
                // 处理15天预报数据...
                JSONObject forecast15d = jsonResponse.getJSONObject("forecast15d");
                if ("0".equals(forecast15d.getString("code"))) {
                    JSONObject forecastData = forecast15d.getJSONObject("data");
                    cached15DayForecasts.clear();
    
                    for (int i = 8; i <= 15; i++) {
                        String dayKey = "d" + i;
                        if (forecastData.has(dayKey)) {
                            JSONObject dayData = forecastData.getJSONObject(dayKey);
                            DailyForecast dailyForecast = parseDailyForecast(dayData, false);
                            cached15DayForecasts.add(dailyForecast);
                        } else {
                            Log.e("MainActivity", "15天数据缺失第" + i + "天，key=" + dayKey);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("MainActivity", "数据解析异常：" + e.getMessage());
                Toast.makeText(this, "数据解析失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void parseHourlyForecast(JSONObject data) {
        try {
            hourlyForecastList.clear();

            if (data.has("hour3data") && !data.isNull("hour3data")) {
                JSONArray hourlyArray = data.getJSONArray("hour3data");
                Log.d("MainActivity", "Found hour3data with " + hourlyArray.length() + " entries");

                for (int i = 0; i < hourlyArray.length(); i++) {
                    String hourDataStr = hourlyArray.getString(i);
                    String[] parts = hourDataStr.split(",");

                    if (parts.length >= 6) {
                        HourlyForecast forecast = new HourlyForecast();

                        // 提取时间（如"11时"）
                        String timeStr = parts[0];
                        String hour = timeStr.substring(timeStr.indexOf("日") + 1);
                        forecast.setHour(hour);

                        // 提取温度（如"27℃"）
                        String temp = parts[3];
                        forecast.setTemp(temp);

                        // 由于小时预报数据中没有最低/最高温度，设为当前温度或默认值
                        forecast.setMinTemp(temp);
                        forecast.setMaxTemp(temp);

                        // 提取天气状况
                        forecast.setWeatherCondition(parts[2]);

                        // 提取天气图标
                        forecast.setWeatherIcon(parts[1]);

                        // 提取风向和风力
                        forecast.setWindDirection(parts[4]);
                        forecast.setWindPower(parts[5]);

                        // 判断是否白天（根据图标代码前缀）
                        boolean isDay = parts[1].startsWith("d");
                        forecast.setDayTime(isDay);

                        hourlyForecastList.add(forecast);
                    }
                }

                // 更新小时预报RecyclerView
                updateHourlyForecastView();
            } else if (data.has("hourly") && !data.isNull("hourly")) {
                // 兼容其他数据格式的处理逻辑
                JSONArray hourlyArray = data.getJSONArray("hourly");

                for (int i = 0; i < hourlyArray.length(); i++) {
                    JSONObject hourData = hourlyArray.getJSONObject(i);

                    HourlyForecast forecast = new HourlyForecast();
                    forecast.setHour(hourData.optString("time", "未知时间"));
                    forecast.setTemp(hourData.optString("temp", "N/A"));
                    forecast.setWeatherCondition(hourData.optString("weather", "未知天气"));
                    forecast.setWeatherIcon(hourData.optString("weather_pic", "d00"));

                    // 设置默认值（根据实际数据结构调整）
                    forecast.setMinTemp("N/A");
                    forecast.setMaxTemp("N/A");
                    forecast.setWindDirection("未知");
                    forecast.setWindPower("未知");

                    hourlyForecastList.add(forecast);
                }

                // 更新小时预报RecyclerView
                updateHourlyForecastView();
            } else {
                Log.e("MainActivity", "未找到小时预报数据，既没有hour3data也没有hourly字段");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("MainActivity", "解析小时预报数据失败: " + e.getMessage());
        }
    }

    private void updateHourlyForecastView() {
        if (hourlyForecastRecyclerView != null && !hourlyForecastList.isEmpty()) {
            HourlyForecastAdapter adapter = new HourlyForecastAdapter(hourlyForecastList, MainActivity.this);
            hourlyForecastRecyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged(); // 通知适配器数据已更新
        } else {
            Log.d("MainActivity", "hourlyForecastList is empty or RecyclerView not initialized");
        }
    }

    private void parseObserve24hData(JSONObject data) {
        try {
            List<Observe24hData> observe24hList = new ArrayList<>();
            Log.d("MainActivity", "开始解析24小时观测数据...");

            if (data.has("observe24h") && !data.isNull("observe24h")) {
                JSONObject observe24hObj = data.getJSONObject("observe24h");
                JSONArray od2Array = observe24hObj.getJSONArray("od2");
                Log.d("MainActivity", "观测数据条目数: " + od2Array.length());

                for (int i = 0; i < od2Array.length(); i++) {
                    JSONObject od2Obj = od2Array.getJSONObject(i);
                    Observe24hData observeData = new Observe24hData();

                    // 设置时间
                    observeData.setTime(od2Obj.optString("od21", "未知时间"));
                    Log.d("MainActivity", "时间: " + observeData.getTime());

                    // 设置温度
                    observeData.setTemperature(od2Obj.optString("od22", "未知温度"));

                    // 设置风向
                    observeData.setWindDirection(od2Obj.optString("od24", "未知风向"));

                    // 设置风力
                    observeData.setWindPower(od2Obj.optString("od25", "未知风力"));

                    // 设置降雨量
                    observeData.setPrecipitation(od2Obj.optString("od26", "未知降雨量"));

                    // 设置湿度
                    observeData.setHumidity(od2Obj.optString("od27", "未知湿度"));

                    // 设置空气质量
                    observeData.setAqi(od2Obj.optString("od28", "未知空气质量"));

                    // 其他字段设置默认值或根据实际情况解析
                    observeData.setWeather("未知天气");
                    observeData.setWeatherCode("d00");
                    observeData.setPressure("未知气压");
                    observeData.setMinTemp("未知最低温");
                    observeData.setMaxTemp("未知最高温");
                    observeData.setDayWindDirection("未知白天风向");
                    observeData.setDayWindPower("未知白天风力");
                    observeData.setNightWindDirection("未知夜晚风向");
                    observeData.setNightWindPower("未知夜晚风力");

                    observe24hList.add(observeData);
                    Log.d("MainActivity", "添加数据项: " + observeData.toString());
                }

                Log.d("MainActivity", "解析完成，共" + observe24hList.size() + "条数据");

                // 新增：反转数据列表顺序
                Collections.reverse(observe24hList);

                // 关键：调用适配器的setData方法而不是未定义的updateObserve24hData
                if (observe24hAdapter != null) {
                    observe24hAdapter.setData(observe24hList);
                } else {
                    Log.e("MainActivity", "observe24hAdapter is null!");
                }
            } else {
                Log.e("MainActivity", "未找到24小时观测数据");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("MainActivity", "解析24小时观测数据失败: " + e.getMessage());
        }
    }

    private String decodeUnicode(String unicodeStr) {
        if (unicodeStr == null) return "";

        Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
        Matcher matcher = pattern.matcher(unicodeStr);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String group = matcher.group(1);
            char ch = (char) Integer.parseInt(group, 16);
            matcher.appendReplacement(sb, String.valueOf(ch));
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            String selectedCity = data.getStringExtra("selectedCity");
            if (selectedCity != null) {
                getSharedPreferences("weather_prefs", MODE_PRIVATE)
                        .edit()
                        .putString("default_city", selectedCity)
                        .apply();
                fetchWeatherData("areaCn", selectedCity);
            }
        }
    }

    private DailyForecast parseDailyForecast(JSONObject dayData, boolean is7DayForecast) throws JSONException {
        DailyForecast dailyForecast = new DailyForecast();

        dailyForecast.setDate(dayData.optString("time", "N/A"));
        dailyForecast.setDayTemp(dayData.optString("temperature_max", "N/A"));
        dailyForecast.setNightTemp(dayData.optString("temperature_min", "N/A"));
        dailyForecast.setDayWeather(dayData.optString("weather", "N/A"));

        if (is7DayForecast) {
            dailyForecast.setDayWindDirection(dayData.optString("wind_day", "N/A"));
            dailyForecast.setNightWindDirection(dayData.optString("wind_night", "N/A"));
        } else {
            dailyForecast.setDayWindDirection(dayData.optString("wind", "N/A"));
            dailyForecast.setNightWindDirection(dayData.optString("wind", "N/A"));
        }

        dailyForecast.setDayWeatherPic(dayData.optString("day_weather_pic", "d00"));
        dailyForecast.setNightWeatherPic(dayData.optString("night_weather_pic", "n00"));

        return dailyForecast;
    }

    private void updateWeatherIcon() {
        String targetPic = isDayTime ? dayWeatherPic : nightWeatherPic;
        int iconRes = getWeatherIconRes(targetPic);
        if (weatherIcon != null) {
            weatherIcon.setImageResource(iconRes);
        }
        if (toggleDayNightBtn != null) {
            toggleDayNightBtn.setText(isDayTime ? "切换夜间" : "切换白天");
        }
    }

    private int getWeatherIconRes(String weatherPic) {
        if (weatherPic == null || weatherPic.isEmpty()) {
            return R.mipmap.d00; // 默认图标
        }

        // 去掉文件扩展名
        String iconName = weatherPic;
        if (iconName.contains(".")) {
            iconName = iconName.substring(0, iconName.indexOf('.'));
        }

        // 获取资源ID
        try {
            return R.mipmap.class.getField(iconName).getInt(null);
        } catch (Exception e) {
            Log.e("WeatherIcon", "获取图标资源失败: " + weatherPic, e);
            return R.mipmap.d00; // 默认图标
        }
    }

    private class ForecastPagerAdapter extends FragmentStateAdapter {
        public ForecastPagerAdapter(@NonNull FragmentManager fragmentManager, Lifecycle lifecycle) {
            super(fragmentManager, lifecycle);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            if (position == 0) {
                return new HourlyForecastFragment();
            } else {
                return new DailyForecastFragment();
            }
        }

        @Override
        public int getItemCount() {
            return 2;
        }
    }
}